{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 12.14 \u5728Unix\u7cfb\u7edf\u4e0a\u9762\u542f\u52a8\u5b88\u62a4\u8fdb\u7a0b\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### \u95ee\u9898\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u4f60\u60f3\u7f16\u5199\u4e00\u4e2a\u4f5c\u4e3a\u4e00\u4e2a\u5728Unix\u6216\u7c7bUnix\u7cfb\u7edf\u4e0a\u9762\u8fd0\u884c\u7684\u5b88\u62a4\u8fdb\u7a0b\u8fd0\u884c\u7684\u7a0b\u5e8f\u3002"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### \u89e3\u51b3\u65b9\u6848\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u521b\u5efa\u4e00\u4e2a\u6b63\u786e\u7684\u5b88\u62a4\u8fdb\u7a0b\u9700\u8981\u4e00\u4e2a\u7cbe\u786e\u7684\u7cfb\u7edf\u8c03\u7528\u5e8f\u5217\u4ee5\u53ca\u5bf9\u4e8e\u7ec6\u8282\u7684\u63a7\u5236\u3002\n\u4e0b\u9762\u7684\u4ee3\u7801\u5c55\u793a\u4e86\u600e\u6837\u5b9a\u4e49\u4e00\u4e2a\u5b88\u62a4\u8fdb\u7a0b\uff0c\u53ef\u4ee5\u542f\u52a8\u540e\u5f88\u5bb9\u6613\u7684\u505c\u6b62\u5b83\u3002"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "#!/usr/bin/env python3\n# daemon.py\n\nimport os\nimport sys\n\nimport atexit\nimport signal\n\ndef daemonize(pidfile, *, stdin='/dev/null',\n                          stdout='/dev/null',\n                          stderr='/dev/null'):\n\n    if os.path.exists(pidfile):\n        raise RuntimeError('Already running')\n\n    # First fork (detaches from parent)\n    try:\n        if os.fork() > 0:\n            raise SystemExit(0)   # Parent exit\n    except OSError as e:\n        raise RuntimeError('fork #1 failed.')\n\n    os.chdir('/')\n    os.umask(0)\n    os.setsid()\n    # Second fork (relinquish session leadership)\n    try:\n        if os.fork() > 0:\n            raise SystemExit(0)\n    except OSError as e:\n        raise RuntimeError('fork #2 failed.')\n\n    # Flush I/O buffers\n    sys.stdout.flush()\n    sys.stderr.flush()\n\n    # Replace file descriptors for stdin, stdout, and stderr\n    with open(stdin, 'rb', 0) as f:\n        os.dup2(f.fileno(), sys.stdin.fileno())\n    with open(stdout, 'ab', 0) as f:\n        os.dup2(f.fileno(), sys.stdout.fileno())\n    with open(stderr, 'ab', 0) as f:\n        os.dup2(f.fileno(), sys.stderr.fileno())\n\n    # Write the PID file\n    with open(pidfile,'w') as f:\n        print(os.getpid(),file=f)\n\n    # Arrange to have the PID file removed on exit/signal\n    atexit.register(lambda: os.remove(pidfile))\n\n    # Signal handler for termination (required)\n    def sigterm_handler(signo, frame):\n        raise SystemExit(1)\n\n    signal.signal(signal.SIGTERM, sigterm_handler)\n\ndef main():\n    import time\n    sys.stdout.write('Daemon started with pid {}\\n'.format(os.getpid()))\n    while True:\n        sys.stdout.write('Daemon Alive! {}\\n'.format(time.ctime()))\n        time.sleep(10)\n\nif __name__ == '__main__':\n    PIDFILE = '/tmp/daemon.pid'\n\n    if len(sys.argv) != 2:\n        print('Usage: {} [start|stop]'.format(sys.argv[0]), file=sys.stderr)\n        raise SystemExit(1)\n\n    if sys.argv[1] == 'start':\n        try:\n            daemonize(PIDFILE,\n                      stdout='/tmp/daemon.log',\n                      stderr='/tmp/dameon.log')\n        except RuntimeError as e:\n            print(e, file=sys.stderr)\n            raise SystemExit(1)\n\n        main()\n\n    elif sys.argv[1] == 'stop':\n        if os.path.exists(PIDFILE):\n            with open(PIDFILE) as f:\n                os.kill(int(f.read()), signal.SIGTERM)\n        else:\n            print('Not running', file=sys.stderr)\n            raise SystemExit(1)\n\n    else:\n        print('Unknown command {!r}'.format(sys.argv[1]), file=sys.stderr)\n        raise SystemExit(1)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u8981\u542f\u52a8\u8fd9\u4e2a\u5b88\u62a4\u8fdb\u7a0b\uff0c\u7528\u6237\u9700\u8981\u4f7f\u7528\u5982\u4e0b\u7684\u547d\u4ee4\uff1a"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "bash % daemon.py start\nbash % cat /tmp/daemon.pid\n2882\nbash % tail -f /tmp/daemon.log\nDaemon started with pid 2882\nDaemon Alive! Fri Oct 12 13:45:37 2012\nDaemon Alive! Fri Oct 12 13:45:47 2012\n..."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u5b88\u62a4\u8fdb\u7a0b\u53ef\u4ee5\u5b8c\u5168\u5728\u540e\u53f0\u8fd0\u884c\uff0c\u56e0\u6b64\u8fd9\u4e2a\u547d\u4ee4\u4f1a\u7acb\u5373\u8fd4\u56de\u3002\n\u4e0d\u8fc7\uff0c\u4f60\u53ef\u4ee5\u50cf\u4e0a\u9762\u90a3\u6837\u67e5\u770b\u4e0e\u5b83\u76f8\u5173\u7684pid\u6587\u4ef6\u548c\u65e5\u5fd7\u3002\u8981\u505c\u6b62\u8fd9\u4e2a\u5b88\u62a4\u8fdb\u7a0b\uff0c\u4f7f\u7528\uff1a"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "bash % daemon.py stop\nbash %"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### \u8ba8\u8bba\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u672c\u8282\u5b9a\u4e49\u4e86\u4e00\u4e2a\u51fd\u6570 daemonize() \uff0c\u5728\u7a0b\u5e8f\u542f\u52a8\u65f6\u88ab\u8c03\u7528\u4f7f\u5f97\u7a0b\u5e8f\u4ee5\u4e00\u4e2a\u5b88\u62a4\u8fdb\u7a0b\u6765\u8fd0\u884c\u3002\ndaemonize() \u51fd\u6570\u53ea\u63a5\u53d7\u5173\u952e\u5b57\u53c2\u6570\uff0c\u8fd9\u6837\u7684\u8bdd\u53ef\u9009\u53c2\u6570\u5728\u88ab\u4f7f\u7528\u65f6\u5c31\u66f4\u6e05\u6670\u4e86\u3002\n\u5b83\u4f1a\u5f3a\u5236\u7528\u6237\u50cf\u4e0b\u9762\u8fd9\u6837\u4f7f\u7528\u5b83\uff1a"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "daemonize('daemon.pid',\n          stdin='/dev/null,\n          stdout='/tmp/daemon.log',\n          stderr='/tmp/daemon.log')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u800c\u4e0d\u662f\u50cf\u4e0b\u9762\u8fd9\u6837\u542b\u7cca\u4e0d\u6e05\u7684\u8c03\u7528\uff1a"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# Illegal. Must use keyword arguments\ndaemonize('daemon.pid',\n          '/dev/null', '/tmp/daemon.log','/tmp/daemon.log')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u521b\u5efa\u4e00\u4e2a\u5b88\u62a4\u8fdb\u7a0b\u7684\u6b65\u9aa4\u770b\u4e0a\u53bb\u4e0d\u662f\u5f88\u6613\u61c2\uff0c\u4f46\u662f\u5927\u4f53\u601d\u60f3\u662f\u8fd9\u6837\u7684\uff0c\n\u9996\u5148\uff0c\u4e00\u4e2a\u5b88\u62a4\u8fdb\u7a0b\u5fc5\u987b\u8981\u4ece\u7236\u8fdb\u7a0b\u4e2d\u8131\u79bb\u3002\n\u8fd9\u662f\u7531 os.fork() \u64cd\u4f5c\u6765\u5b8c\u6210\u7684\uff0c\u5e76\u7acb\u5373\u88ab\u7236\u8fdb\u7a0b\u7ec8\u6b62\u3002"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u5728\u5b50\u8fdb\u7a0b\u53d8\u6210\u5b64\u513f\u540e\uff0c\u8c03\u7528 os.setsid() \u521b\u5efa\u4e86\u4e00\u4e2a\u5168\u65b0\u7684\u8fdb\u7a0b\u4f1a\u8bdd\uff0c\u5e76\u8bbe\u7f6e\u5b50\u8fdb\u7a0b\u4e3a\u9996\u9886\u3002\n\u5b83\u4f1a\u8bbe\u7f6e\u8fd9\u4e2a\u5b50\u8fdb\u7a0b\u4e3a\u65b0\u7684\u8fdb\u7a0b\u7ec4\u7684\u9996\u9886\uff0c\u5e76\u786e\u4fdd\u4e0d\u4f1a\u518d\u6709\u63a7\u5236\u7ec8\u7aef\u3002\n\u5982\u679c\u8fd9\u4e9b\u542c\u4e0a\u53bb\u592a\u9b54\u5e7b\uff0c\u56e0\u4e3a\u5b83\u9700\u8981\u5c06\u5b88\u62a4\u8fdb\u7a0b\u540c\u7ec8\u7aef\u5206\u79bb\u5f00\u5e76\u786e\u4fdd\u4fe1\u53f7\u673a\u5236\u5bf9\u5b83\u4e0d\u8d77\u4f5c\u7528\u3002\n\u8c03\u7528 os.chdir() \u548c os.umask(0) \u6539\u53d8\u4e86\u5f53\u524d\u5de5\u4f5c\u76ee\u5f55\u5e76\u91cd\u7f6e\u6587\u4ef6\u6743\u9650\u63a9\u7801\u3002\n\u4fee\u6539\u76ee\u5f55\u901a\u5e38\u662f\u4e2a\u597d\u4e3b\u610f\uff0c\u56e0\u4e3a\u8fd9\u6837\u53ef\u4ee5\u4f7f\u5f97\u5b83\u4e0d\u518d\u5de5\u4f5c\u5728\u88ab\u542f\u52a8\u65f6\u7684\u76ee\u5f55\u3002"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u53e6\u5916\u4e00\u4e2a\u8c03\u7528 os.fork() \u5728\u8fd9\u91cc\u66f4\u52a0\u795e\u79d8\u70b9\u3002\n\u8fd9\u4e00\u6b65\u4f7f\u5f97\u5b88\u62a4\u8fdb\u7a0b\u5931\u53bb\u4e86\u83b7\u53d6\u65b0\u7684\u63a7\u5236\u7ec8\u7aef\u7684\u80fd\u529b\u5e76\u4e14\u8ba9\u5b83\u66f4\u52a0\u72ec\u7acb\n\uff08\u672c\u8d28\u4e0a\uff0c\u8be5daemon\u653e\u5f03\u4e86\u5b83\u7684\u4f1a\u8bdd\u9996\u9886\u4f4e\u4f4d\uff0c\u56e0\u6b64\u518d\u4e5f\u6ca1\u6709\u6743\u9650\u53bb\u6253\u5f00\u63a7\u5236\u7ec8\u7aef\u4e86\uff09\u3002\n\u5c3d\u7ba1\u4f60\u53ef\u4ee5\u5ffd\u7565\u8fd9\u4e00\u6b65\uff0c\u4f46\u662f\u6700\u597d\u4e0d\u8981\u8fd9\u4e48\u505a\u3002"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u4e00\u65e6\u5b88\u62a4\u8fdb\u7a0b\u88ab\u6b63\u786e\u7684\u5206\u79bb\uff0c\u5b83\u4f1a\u91cd\u65b0\u521d\u59cb\u5316\u6807\u51c6I/O\u6d41\u6307\u5411\u7528\u6237\u6307\u5b9a\u7684\u6587\u4ef6\u3002\n\u8fd9\u4e00\u90e8\u5206\u6709\u70b9\u96be\u61c2\u3002\u8ddf\u6807\u51c6I/O\u6d41\u76f8\u5173\u7684\u6587\u4ef6\u5bf9\u8c61\u7684\u5f15\u7528\u5728\u89e3\u91ca\u5668\u4e2d\u591a\u4e2a\u5730\u65b9\u88ab\u627e\u5230\n\uff08sys.stdout, sys.__stdout__\u7b49\uff09\u3002\n\u4ec5\u4ec5\u7b80\u5355\u7684\u5173\u95ed sys.stdout \u5e76\u91cd\u65b0\u6307\u5b9a\u5b83\u662f\u884c\u4e0d\u901a\u7684\uff0c\n\u56e0\u4e3a\u6ca1\u529e\u6cd5\u77e5\u9053\u5b83\u662f\u5426\u5168\u90e8\u90fd\u662f\u7528\u7684\u662f sys.stdout \u3002\n\u8fd9\u91cc\uff0c\u6211\u4eec\u6253\u5f00\u4e86\u4e00\u4e2a\u5355\u72ec\u7684\u6587\u4ef6\u5bf9\u8c61\uff0c\u5e76\u8c03\u7528 os.dup2() \uff0c\n\u7528\u5b83\u6765\u4ee3\u66ff\u88ab sys.stdout \u4f7f\u7528\u7684\u6587\u4ef6\u63cf\u8ff0\u7b26\u3002\n\u8fd9\u6837\uff0csys.stdout \u4f7f\u7528\u7684\u539f\u59cb\u6587\u4ef6\u4f1a\u88ab\u5173\u95ed\u5e76\u7531\u65b0\u7684\u6765\u66ff\u6362\u3002\n\u8fd8\u8981\u5f3a\u8c03\u7684\u662f\u4efb\u4f55\u7528\u4e8e\u6587\u4ef6\u7f16\u7801\u6216\u6587\u672c\u5904\u7406\u7684\u6807\u51c6I/O\u6d41\u8fd8\u4f1a\u4fdd\u7559\u539f\u72b6\u3002"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u5b88\u62a4\u8fdb\u7a0b\u7684\u4e00\u4e2a\u901a\u5e38\u5b9e\u8df5\u662f\u5728\u4e00\u4e2a\u6587\u4ef6\u4e2d\u5199\u5165\u8fdb\u7a0bID\uff0c\u53ef\u4ee5\u88ab\u5176\u4ed6\u7a0b\u5e8f\u540e\u9762\u4f7f\u7528\u5230\u3002\ndaemonize() \u51fd\u6570\u7684\u6700\u540e\u90e8\u5206\u5199\u4e86\u8fd9\u4e2a\u6587\u4ef6\uff0c\u4f46\u662f\u5728\u7a0b\u5e8f\u7ec8\u6b62\u65f6\u5220\u9664\u4e86\u5b83\u3002\natexit.register() \u51fd\u6570\u6ce8\u518c\u4e86\u4e00\u4e2a\u51fd\u6570\u5728Python\u89e3\u91ca\u5668\u7ec8\u6b62\u65f6\u6267\u884c\u3002\n\u4e00\u4e2a\u5bf9\u4e8eSIGTERM\u7684\u4fe1\u53f7\u5904\u7406\u5668\u7684\u5b9a\u4e49\u540c\u6837\u9700\u8981\u88ab\u4f18\u96c5\u7684\u5173\u95ed\u3002\n\u4fe1\u53f7\u5904\u7406\u5668\u7b80\u5355\u7684\u629b\u51fa\u4e86 SystemExit() \u5f02\u5e38\u3002\n\u6216\u8bb8\u8fd9\u4e00\u6b65\u770b\u4e0a\u53bb\u6ca1\u5fc5\u8981\uff0c\u4f46\u662f\u6ca1\u6709\u5b83\uff0c\n\u7ec8\u6b62\u4fe1\u53f7\u4f1a\u4f7f\u5f97\u4e0d\u6267\u884c atexit.register() \u6ce8\u518c\u7684\u6e05\u7406\u64cd\u4f5c\u7684\u65f6\u5019\u5c31\u6740\u6389\u4e86\u89e3\u91ca\u5668\u3002\n\u4e00\u4e2a\u6740\u6389\u8fdb\u7a0b\u7684\u4f8b\u5b50\u4ee3\u7801\u53ef\u4ee5\u5728\u7a0b\u5e8f\u6700\u540e\u7684 stop \u547d\u4ee4\u7684\u64cd\u4f5c\u4e2d\u770b\u5230\u3002"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u66f4\u591a\u5173\u4e8e\u7f16\u5199\u5b88\u62a4\u8fdb\u7a0b\u7684\u4fe1\u606f\u53ef\u4ee5\u67e5\u770b\u300aUNIX \u73af\u5883\u9ad8\u7ea7\u7f16\u7a0b\u300b, \u7b2c\u4e8c\u7248\nby W. Richard Stevens and Stephen A. Rago (Addison-Wesley, 2005)\u3002\n\u5c3d\u7ba1\u5b83\u662f\u5173\u6ce8\u4e0eC\u8bed\u8a00\u7f16\u7a0b\uff0c\u4f46\u662f\u6240\u6709\u7684\u5185\u5bb9\u90fd\u9002\u7528\u4e8ePython\uff0c\n\u56e0\u4e3a\u6240\u6709\u9700\u8981\u7684POSIX\u51fd\u6570\u90fd\u53ef\u4ee5\u5728\u6807\u51c6\u5e93\u4e2d\u627e\u5230\u3002"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.7.1"
    },
    "toc": {
      "base_numbering": 1,
      "nav_menu": {},
      "number_sections": true,
      "sideBar": true,
      "skip_h1_title": true,
      "title_cell": "Table of Contents",
      "title_sidebar": "Contents",
      "toc_cell": false,
      "toc_position": {},
      "toc_section_display": true,
      "toc_window_display": true
    }
  },
  "nbformat": 4,
  "nbformat_minor": 2
}